package net.example.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.Log;
import android.util.Size;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.oraycn.esbasic.helpers.ImageHelper;
import com.oraycn.esbasic.helpers.StringHelper;
import com.oraycn.esbasic.listeners.ZoomImageListener;
import com.oraycn.esbasic.objectManagement.LimitQueue;
import com.oraycn.esbasic.objectManagement.cache.HotCache;
import com.oraycn.esbasic.objectManagement.managers.ObjectManager;
import com.oraycn.esbasic.tools.KeyboardHeight.OnSoftKeyBoardChangeListener;
import com.oraycn.esbasic.tools.KeyboardHeight.PreventKeyboardBlockUtil;
import com.oraycn.esframework.core.ClientType;
import com.oraycn.esframework.core.FileEventListener;
import com.oraycn.omcs.MultimediaManagerFactory;
import com.oraycn.omcs.shortMessages.AudioMessage;
import com.oraycn.omcs.shortMessages.IAudioMessagePlayer;
import com.oraycn.omcs.shortMessages.IAudioPlayerCallback;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;

import net.example.activity.adapter.ChatLVAdapter;
import net.example.activity.adapter.FaceGVAdapter;
import net.example.activity.adapter.FaceVPAdapter;
import net.example.activity.adapter.interfaces.IAdapterEventCallback;
import net.example.activity.view.AudioPressedButton;
import net.example.activity.view.DropdownListView;
import net.example.activity.view.MyEditText;
import net.example.activity.view.sessionview.MessageItem;
import net.example.db.ChatMessageRecordPersister;
import net.example.db.LastChatRecordPersister;
import net.example.ggtalk.R;
import net.example.manager.ClientGlobalCache;
import net.example.manager.GGApplication;
import net.example.manager.Manager;
import net.example.model.ChatInfo;
import net.example.model.ContractType;
import net.example.model.FileMessage;
import net.example.model.FileTransferUseType;
import net.example.model.GGGroup;
import net.example.model.GGUser;
import net.example.model.Group_Friend_SelectorType;
import net.example.model.SnapchatMessage;
import net.example.model.UserBasicModel;
import net.example.model.UserState;
import net.example.model.UserStatus;
import net.example.model.common.ChatBoxElemnetType;
import net.example.model.common.ChatEventType;
import net.example.model.common.NonText;
import net.example.model.common.RichChatMessage;
import net.example.model.event.ChatEvent;
import net.example.model.event.ClickToChatEvent;
import net.example.model.event.FileEvent;
import net.example.model.event.FriendCommentNameChangedEvent;
import net.example.model.event.FriendDeletedNotifyEvent;
import net.example.model.event.GroupBan4GroupEvent;
import net.example.model.event.GroupBan4UserEvent;
import net.example.model.event.GroupDeletedNotifyEvent;
import net.example.model.event.GroupInfoChangedEvent;
import net.example.model.event.GroupUserChangedEvent;
import net.example.model.event.RemoveGroupBan4GroupEvent;
import net.example.model.event.RemoveGroupBan4UserEvent;
import net.example.model.event.SnapchatMessageReadEvent;
import net.example.model.event.UserEvent;
import net.example.model.event.UserInfoChangedEvent;
import net.example.utils.ConfigUtils;
import net.example.utils.FileHelper;
import net.example.utils.FileUtils;
import net.example.utils.HeadImgHelper;
import net.example.utils.IntentUtils;
import net.example.utils.LogHelper;
import net.example.utils.SDKUtil;
import net.example.utils.ToastUtils;
import net.example.utils.android.AndroidUI;
import net.example.utils.android.AndroidUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.greenrobot.event.EventBus;

public class ChatActivity extends Activity implements View.OnClickListener,
        DropdownListView.OnRefreshListenerHeader, IAudioPlayerCallback, IAdapterEventCallback {
    private static final int SELECT_FILE = 200;
    private static final int SELECT_IMG = 201;
    private static final int TAKE_PICTURE = 202;
    private static final int Share_Message=300;
    private static final int At_MemberInGroup =301;
    private static final int VideoMemberInGroup=302;
    private ViewPager mViewPager;
    private LinearLayout mDotsLayout;
    private MyEditText input;
    private Button send;
    private DropdownListView mListView;
    private ChatLVAdapter mLvAdapter;
    private LinearLayout chat_face_container;
    private LinearLayout bottom;
    private LinearLayout bottom_ban;
    private ViewGroup input_box;
    private TextView tv_banTips;
    private ImageView image_face;// 表情图标
    private ImageView chatFullImg;
    ImageButton downLoad_btn;//下载图片按钮
    private ViewGroup chart_all;
    private int columns = 6;
    private int rows = 4;
    private List<View> views = new ArrayList<View>();
    private LinkedList<ChatInfo> infos = new LinkedList<ChatInfo>();
    private SimpleDateFormat sd;
    private LinearLayout btnContainer;
    private Button btnMore;
    private AudioPressedButton buttonSpeak;
    private View buttonPressToSpeak;
    private View buttonSetModeKeyboard;
    private View buttonSetModeVoice;
    private String TalkingType;
    private String TalkingID;
    private int pageSize = 10;
    private int pageIndex = 0;
    private Vibrator vibrator;
    private String reply = "";
    private ViewGroup titlePanel;
    TextView header ;
    ImageView ct_photo;
    RelativeLayout headerLayout;
    Uri imageUri;
    private ZoomImageListener zoomImageListener;
    private int currentAudioInfoPosition=-1;//-1:未有语音在播放
    private boolean isExistAllGroupBan=false;//该群是否存在全员禁言
    private boolean isGroupCreator=false;//当前用户是否为该群的创建者
    private ObjectManager<String,String> atSelectedUserManager=new ObjectManager<>();//被@的成员集合 key: userID,value:userName

    private Timer timer;
    private CountdownTimerTask countdownTimerTask;
    private List<Integer> snapchatMessageList =new ArrayList<>();
    private boolean isSnapchating =false; //是否处于编写阅后即焚消息状态

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            setContentView(R.layout.chat_main);
            // android 7.0系统解决拍照的问题
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
            initStaticFaces();
            initViews();
            hideSoftInputView();
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
            AndroidUtil.CloseSpeaker(ChatActivity.this, AndroidUtil.getCurrentVolume(ChatActivity.this));
            AndroidUtil.OpenSpeaker(ChatActivity.this);
            ClientGlobalCache.getInstance().removeNotReadMsg(this.TalkingID);
            EventBus.getDefault().post(new ClickToChatEvent(this.TalkingID));
            countdownTimerTask=new CountdownTimerTask();
            timer=new Timer(false);
            timer.scheduleAtFixedRate(countdownTimerTask ,0,1000);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void playFinished(AudioMessage message) {
        message.setAnimation(false);
        Message msg = mHandler.obtainMessage(1);
        mHandler.sendMessage(msg);
    }

    @Override
    public void playInterrupted(AudioMessage message) {
        message.setAnimation(false);
        Message msg = mHandler.obtainMessage(1);
        mHandler.sendMessage(msg);
    }

    //region IAdapterEventCallback
    @Override
    public void onImageClicked(ChatInfo chatInfo) {
        try {
            if (chatInfo != null) {
                this.imageClick(chatInfo.getImageUrl());
            }
        }catch(Exception ex){
        }
    }

    private void imageClick(String imageUrl)
    {
        chart_all.setVisibility(View.VISIBLE);
        bottom.setVisibility(View.GONE);
        downLoad_btn.setVisibility(View.VISIBLE);
        downLoad_btn.setTag(imageUrl);
        BitmapFactory.Options options = new BitmapFactory.Options();
        /**
         * 最关键在此，把options.inJustDecodeBounds = true;
         * 这里再decodeFile()，返回的bitmap为空，但此时调用options.outHeight时，已经包含了图片的高了
         */
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imageUrl,options);
        zoomImageListener.setImgSize(options.outWidth,options.outHeight);
        Picasso.get().load(new File(imageUrl)).error(R.drawable.default_image).memoryPolicy(MemoryPolicy.NO_CACHE,MemoryPolicy.NO_STORE).into(chatFullImg);

    }

    public void onAudioClicked(int position, AudioMessage audioMessage)
    {
        this.OpenSpeaker();
        IAudioMessagePlayer audioPlayer = MultimediaManagerFactory.GetSingleton().getAudioMessagePlayer();
        audioPlayer.setAudioPlayerCallback(this);
        audioPlayer.stop();
        if(this.currentAudioInfoPosition == position)
        {
            this.currentAudioInfoPosition =-1;
            return;
        }
        audioPlayer.play(audioMessage);
        this.currentAudioInfoPosition = position;
    }

    public void onFileClicked(ChatInfo chatInfo)
    {
        if(chatInfo==null)
        {
            return;
        }
        FileMessage fileMessage=chatInfo.getFileMessage();
        if(fileMessage==null)
        {
            return;
        }
        if(FileHelper.isImgFile(fileMessage.fileName))
        {
            this.imageClick(fileMessage.filePath);
        }else if(FileHelper.isAudioFile(fileMessage.fileName))
        {

        }
    }

    public void onSnapchatMessageClicked(int position)
    {
        try {
            ChatInfo chatInfo=this.infos.get(position);
            this.snapchatMessageList.add(position);
            ClientGlobalCache.getInstance().DeleteChatMessageRecordInLocalDB(this.TalkingID,chatInfo.getAutoID());//删除DB中该条聊天记录
            String messageID= chatInfo.snapchatMessageID.split("-")[1];
            Manager.getInstance().sendSnapchatReadMessage(new SnapchatMessage(messageID,chatInfo.getSpeakerID(),chatInfo.getRichChatMessage()));
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }
    private static final Object staticLockObj = new Object();
    public void onSnapchatMessageTimeover(int position)
    {
        synchronized (staticLockObj) {
            this.infos.remove(position);//移除界面中的该行
            for (int i = 0; i < snapchatMessageList.size(); i++) {
                int tempPosition = snapchatMessageList.get(i);
                if (tempPosition > position) {
                    tempPosition--;
                    this.snapchatMessageList.set(i,tempPosition);
                }
            }
        }
        this.mLvAdapter.notifyDataSetChanged();
    }
    //endregion

    private class CountdownTimerTask extends TimerTask
    {
        public CountdownTimerTask()
        {

        }
        @Override
        public void run() {
            try {
                for (int i = snapchatMessageList.size() - 1; i >= 0; i--) {
                    synchronized(staticLockObj){
                        int position = snapchatMessageList.get(i);
                        ChatInfo chatInfo = infos.get(position);
                        chatInfo.setIsRead(true);
                        if (chatInfo.snapchatMessageShowSeconds >= 0) {
                            Message msg = mHandler.obtainMessage(4);
                            msg.arg1 = position;//position
                            msg.arg2 = chatInfo.snapchatMessageShowSeconds;//倒计时显示的秒数
                            mHandler.sendMessage(msg);
                            if (chatInfo.snapchatMessageShowSeconds == 0) {
                                snapchatMessageList.remove(i);
                                break;
                            }
                            chatInfo.snapchatMessageShowSeconds--;
                        }
                    }

                }
            }catch (Exception e)
            {
                e.printStackTrace();
            }

        }
    }

    private ChatInfo currentShareChatInfo=null;
    @Override
    public void onShareMessage(ChatInfo chatInfo) {
        this.currentShareChatInfo=chatInfo;
       Intent intent=  new Intent(this, Group_Friend_SelectorActivity.class);
       intent.putExtra("talkingID",TalkingID);
       intent.putExtra("groupFriendSelectorType", Group_Friend_SelectorType.ShareMessage);
       startActivityForResult(intent, Share_Message);
    }
    //准备音频环境  （设置语音消息回调、打开扬声器）
    private void prepareAudioContext() {
        if (MultimediaManagerFactory.GetSingleton().getAudioMessageController() != null && !MultimediaManagerFactory.GetSingleton().getAudioMessageController().isInitialized()) {
            MultimediaManagerFactory.GetSingleton().getAudioMessageController().initialize();
        }
//        this.OpenSpeaker();
    }
    private void closeAudioContext() {
        MultimediaManagerFactory.GetSingleton().getAudioMessageController().dispose();
        AndroidUtil.CloseSpeaker(ChatActivity.this, AndroidUtil.getCurrentVolume(ChatActivity.this));
    }
    //打开扬声器
    private void OpenSpeaker()
    {
        if (!AndroidUtil.isSpeakerphoneOn(ChatActivity.this)) {
            AndroidUtil.CloseSpeaker(ChatActivity.this, AndroidUtil.getCurrentVolume(ChatActivity.this));
            AndroidUtil.OpenSpeaker(ChatActivity.this);
        }
    }


    ScheduledExecutorService executor= null;
    AudioPressedButton.PressCallback pressCallback=new AudioPressedButton.PressCallback() {
        @Override
        public boolean setRecordEnabled() {
            prepareAudioContext();
            return true;
        }

        @Override
        public void onStartRecord() {
            try {
                if (SDKUtil.checkConnection()) {
                    MultimediaManagerFactory.GetSingleton().getAudioMessageController().startCapture();
                    if(executor==null|| executor.isShutdown()||executor.isTerminated())
                    {
                        executor= Executors.newScheduledThreadPool(1);
                    }
                    executor.scheduleAtFixedRate(new Runnable() {
                        @Override
                        public void run() {
                            int volume = (int) (Math.random() * 30000);
                            Message message= mHandler.obtainMessage(5);
                            message.arg1=volume;
                            mHandler.sendMessage(message);
                        }
                    },1,300,TimeUnit.MILLISECONDS);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }

        @Override
        public void onStopRecord() {
            try {
                executor.shutdown();
                if (SDKUtil.checkConnection()) {
                    AudioMessage message = MultimediaManagerFactory.GetSingleton().getAudioMessageController().stopCapture();
                    if (message != null) {
                        if (message.spanInMSecs > 1000) {
                            ChatInfo info = ChatInfo.getChatInfo(GGApplication.getInstance().getCurrentUser().getUserID(), TalkingID, message, true, new Date());
                            addChatInfoAndDisplay(info);
                            GGApplication.getInstance().getEngine().sendMessage(TalkingID, ContractType.AudioMessage.getType(), message.serialize(), null, true);
                        } else {
                            ToastUtils.showShort(ChatActivity.this.getApplication(), "时间太短！");
                        }
                    }
                }
                closeAudioContext();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onCancelRecord() {
            MultimediaManagerFactory.GetSingleton().getAudioMessageController().stopCapture();
            closeAudioContext();
            executor.shutdown();
        }
    };

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                //下拉刷新
                case 0:
                    List<ChatInfo> list =(List<ChatInfo>)msg.obj;
                    if (list.size() <= 0) {
                        ToastUtils.showLong(ChatActivity.this, "无更多数据");
                        return;
                    }
                    pageIndex++;
                    synchronized (staticLockObj) {
                        infos.addAll(0, list);
                        for (int i = 0; i < snapchatMessageList.size(); i++) {
                            int tempPosition= snapchatMessageList.get(i);
                            tempPosition += list.size();
                            snapchatMessageList.set(i,tempPosition);
                        }
                        mListView.setSelection(0);
                        mLvAdapter.notifyDataSetChanged();
                    }
                    break;
                case 1:
                 //  mLvAdapter.notifyDataSetChanged();
                    currentAudioInfoPosition=-1;
                    break;
                case 2:
                    mListView.setSelection(infos.size() - 1);
                    break;
                case 3://转发成功
                    ToastUtils.showLong(ChatActivity.this, "已发送");
                    break;
                case 4://阅后即焚消息倒计时
                    int position=msg.arg1;
                    int countdownSec=msg.arg2;
                    if(countdownSec<=0)
                    {
                        onSnapchatMessageTimeover(position);
                        return;
                    }
                    mLvAdapter.updateItem(position,mListView);
                    break;
                case 5:
                    int volume=msg.arg1;
                    buttonSpeak.setVolume(volume);
                    break;
            }
        }
    };

    @SuppressLint("SimpleDateFormat")
    private void initViews() {
        try {
            vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            input_box =(ViewGroup) findViewById(R.id.input_box);
            btnContainer = (LinearLayout) findViewById(R.id.ll_btn_container);
             btnMore = (Button) findViewById(R.id.btn_more);
            buttonPressToSpeak = findViewById(R.id.btn_press_to_speak);
            buttonSpeak = (AudioPressedButton) findViewById(R.id.but_postLogin);
            buttonSpeak.setCallback(pressCallback);
            bottom = (LinearLayout) findViewById(R.id.bottom);
            bottom_ban =(LinearLayout)findViewById(R.id.bottom_ban);
            tv_banTips=(TextView)findViewById(R.id.banTips);
//            buttonSpeak.setOnTouchListener(new ButtonListener());
            buttonSetModeVoice = findViewById(R.id.btn_set_mode_voice);
            buttonSetModeKeyboard = findViewById(R.id.btn_set_mode_keyboard);
            ImageView btn_more_detail=(ImageView)findViewById(R.id.btn_more_detail);
            btn_more_detail.setVisibility(View.VISIBLE);
            sd = new SimpleDateFormat();
            titlePanel=(ViewGroup)findViewById(R.id.header);
            header = ((TextView) findViewById(R.id.headerText));
            ct_photo = ((ImageView) findViewById(R.id.ct_photo));
            headerLayout = ((RelativeLayout) findViewById(R.id.center_header));
            chart_all = (ViewGroup) findViewById(R.id.chart_all);
//            chart_all.setOnClickListener(new ImageAlertClick());
            chatFullImg = (ImageView) findViewById(R.id.chatAll);
            downLoad_btn=(ImageButton) findViewById(R.id.image_download);
            downLoad_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d("点击下载", "onClick: ");
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    String path=downLoad_btn.getTag().toString();
                    String picName=FileUtils.getFileName(path);
                    Bitmap bitmap= BitmapFactory.decodeFile(path,options);
                    FileUtils.saveBitmapToDCIM(ChatActivity.this,bitmap,picName);
                    downLoad_btn.setVisibility(View.GONE);
                }
            });
            zoomImageListener=new ZoomImageListener(this);
            zoomImageListener.setOnClickListener(new ImageAlertClick());
            zoomImageListener.setImageView(chatFullImg);
            chatFullImg.setOnTouchListener(zoomImageListener);
            this.TalkingType = getIntent().getStringExtra(ConfigUtils.TalkingType);
            if (!this.TalkingType.equals(ConfigUtils.Person_Talking)) {
                findViewById(R.id.container_file).setVisibility(View.GONE); //可以群文件
                //findViewById(R.id.container_video_call).setVisibility(View.GONE);//可以群视频
                findViewById(R.id.container_voice_call).setVisibility(View.GONE);
                findViewById(R.id.container_snapchat).setVisibility(View.GONE);
            }
            this.TalkingID = getIntent().getStringExtra(this.TalkingType);

            //若聊天对象是自己，隐藏视频、语音通话 功能
            if(this.TalkingID.equals(ClientGlobalCache.getInstance().getCurrentUser().getUserID()))
            {
                findViewById(R.id.container_video_call).setVisibility(View.GONE);
                findViewById(R.id.container_voice_call).setVisibility(View.GONE);
                findViewById(R.id.container_snapchat).setVisibility(View.GONE);
                ct_photo.setVisibility(View.GONE);
                buttonSetModeVoice.setVisibility(View.GONE);
            }
            LimitQueue<ChatInfo> queue= ClientGlobalCache.getInstance().getChatInfos(this.TalkingID);
            if(queue==null)
            {
                List<ChatInfo> chatInfos= getHistoryChatInfo();
                infos.addAll(chatInfos);
                ClientGlobalCache.getInstance().addChatInfos(this.TalkingID,chatInfos);
            }
            else {
                infos.addAll(queue.getQueue());
            }
            mListView = (DropdownListView) findViewById(R.id.message_chat_listview);
            mLvAdapter = new ChatLVAdapter(this, infos, mListView, this);
            mLvAdapter.setList(infos);
            mListView.setAdapter(mLvAdapter);
            // 表情图标
            image_face = (ImageView) findViewById(R.id.image_face);
            // 表情布局
            chat_face_container = (LinearLayout) findViewById(R.id.chat_face_container);
            mViewPager = (ViewPager) findViewById(R.id.face_viewpager);
            mViewPager.setOnPageChangeListener(new PageChange());
            // 表情下小圆点
            mDotsLayout = (LinearLayout) findViewById(R.id.face_dots_container);
            input = (MyEditText) findViewById(R.id.input_sms);
            input.setOnClickListener(this);
            send = (Button) findViewById(R.id.send_sms);
            InitViewPager();
            // 表情按钮
            image_face.setOnClickListener(this);
            // 发送
            send.setOnClickListener(this);
            mListView.setSelection(infos.size() - 1);
            mListView.setOnRefreshListenerHead(this);
            mListView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
                        if (chat_face_container.getVisibility() == View.VISIBLE) {
                            chat_face_container.setVisibility(View.GONE);
                        }
                        btnContainer.setVisibility(View.GONE);
                        hideSoftInputView();// 隐藏软键盘
                    }
                    return false;
                }
            });

            if(ClientGlobalCache.getInstance().getCurrentUser().UserState== UserState.NoSpeaking)
            {
                this.setControl_GroupBan(true);
            }
            // 监听文字框
            input.addTextChangedListener(new TextWatcher() {
                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                                          int count) {
                    if (!TextUtils.isEmpty(s)) {
                        if(s.charAt(s.length()-1)=='@'&& TalkingType.equals(ConfigUtils.Group_Talking))
                        {
                            moveToSelectAtMemberIDs();
                        }
                        btnMore.setVisibility(View.GONE);
                        send.setVisibility(View.VISIBLE);
                    } else {
                        btnMore.setVisibility(View.VISIBLE);
                        send.setVisibility(View.GONE);
                    }
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

                @Override
                public void afterTextChanged(Editable s) {}
            });

            if (this.TalkingType.equals(ConfigUtils.Person_Talking)) {
                updateUserStatus(false);

            } else if (this.TalkingType.equals(ConfigUtils.Group_Talking)) {
                buttonSetModeVoice.setVisibility(View.GONE);
                this.setGroupHeader();
                this.isExistAllGroupBan=Manager.getInstance().existAllGroupBan(this.TalkingID);
                this.isGroupCreator=this.isGroupCreator();
                if(this.isExistAllGroupBan)
                {
                    if(!this.isGroupCreator)
                    {
                        this.setControl_GroupBan(true);
                    }
                }else {
                    Manager.getInstance().checkGroupBan4CurrentUser(this.TalkingID);
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    private void moveToSelectAtMemberIDs()
    {
        Intent intent=  new Intent(this, Group_Friend_SelectorActivity.class);
        intent.putExtra("groupID",TalkingID);
        intent.putExtra("groupFriendSelectorType", Group_Friend_SelectorType.AtMemberInGroup);
        startActivityForResult(intent, At_MemberInGroup);
    }

    /**
     * 设置禁言相关控件
     * @param isBan 是否被禁言
     * */
    private void setControl_GroupBan(boolean isBan)
    {
        if(isBan)
        {
            bottom.setVisibility(View.GONE);
            bottom_ban.setVisibility(View.VISIBLE);
            RelativeLayout.LayoutParams listViewParams=(RelativeLayout.LayoutParams) mListView.getLayoutParams();
            listViewParams.addRule(RelativeLayout.ABOVE,R.id.bottom_ban);
        }
        else {
            bottom.setVisibility(View.VISIBLE);
            bottom_ban.setVisibility(View.GONE);
            RelativeLayout.LayoutParams listViewParams=(RelativeLayout.LayoutParams) mListView.getLayoutParams();
            listViewParams.addRule(RelativeLayout.ABOVE,R.id.bottom);
        }
    }

    private void updateUserStatus(boolean changed) {
        if(this.TalkingID.equals(ClientGlobalCache.getInstance().getCurrentUser().getUserID()))
        {
            ct_photo.setVisibility(View.GONE);
            header.setText("文件传输助手");
            return;
        }
        GGUser GGUser = ClientGlobalCache.getInstance().getUser(this.TalkingID);
        if(GGUser !=null) {
            ct_photo.setVisibility(View.VISIBLE);
            HeadImgHelper.setUserHeadImg(ct_photo, GGUser);
            UserStatus.setImageBackgroundGrayByStatus(GGUser.getUserStatus(), ct_photo, null);
            header.setText(GGUser.getCommentName());
            if (changed) {
                AndroidUI.animationAlpha(headerLayout);
            }
        }
    }

    //设置黑名单界面 隐藏发送按钮
    private void setBlackBlackListView(String tips)
    {
        bottom.setVisibility(View.GONE);
        tv_banTips.setText(tips);
        bottom_ban.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View arg0) {
        if (SDKUtil.checkConnection()) {
            switch (arg0.getId()) {
                case R.id.input_sms:// 输入框
                    if (chat_face_container.getVisibility() == View.VISIBLE) {
                        chat_face_container.setVisibility(View.GONE);
                    }
                    if(btnContainer.getVisibility()==View.VISIBLE)
                    {
                        btnContainer.setVisibility(View.GONE);
                    }
                    break;
                case R.id.image_face:
                    // 隐藏软键盘
                    hideSoftInputView();
                    // 表情
                    if (chat_face_container.getVisibility() == View.GONE) {
                        chat_face_container.setVisibility(View.VISIBLE);
                    } else {
                        chat_face_container.setVisibility(View.GONE);
                    }
                    break;
                case R.id.send_sms:
                    // 发送
                    reply = input.getText().toString();
                    if (!TextUtils.isEmpty(reply)) {
                        RichChatMessage chatContent=this.GetChatContent(reply);
                        boolean isSent=false;//消息是否发送成功
                        String snapchatMessageID=String.valueOf(new Date().getTime());
                        ChatInfo info = ChatInfo.getChatInfo(GGApplication.getInstance().getCurrentUser().getUserID(), this.TalkingID, reply, true,new Date());
                        if(this.isSnapchating)
                        {
                            SnapchatMessage snapchatMessage=new SnapchatMessage(snapchatMessageID ,ClientGlobalCache.getInstance().getCurrentUser().getUserID(),chatContent);
                            isSent=  Manager.getInstance().sendSnapchatMessage(this.TalkingID,snapchatMessage);
                            info.snapchatMessageID = snapchatMessage.GetUniqueID();
                        }
                        else {
                            isSent=  this.sendMsg(chatContent);
                        }
                        if(!isSent)
                        {
                            ToastUtils.showShort(this,"发送失败！");
                            return;
                        }
                        info.setRichChatMessage(chatContent);
                        addChatInfoAndDisplay(info);
                        input.setText("");
                    }
                    break;
                case R.id.btn_picture:
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    try {
                        startActivityForResult(Intent.createChooser(intent, "请选择一个要上传的图片"), SELECT_IMG);
                        btnContainer.setVisibility(View.GONE);
                    } catch (android.content.ActivityNotFoundException ex) {
                        ToastUtils.showShort(this.getApplication(), "请安装文件管理器");
                    }
                    break;

                case R.id.btn_file:
                    if(this.TalkingType.equals(ConfigUtils.Person_Talking))//点对点视频
                    {
                        Intent intentFile = new Intent(Intent.ACTION_GET_CONTENT);
                        intentFile.setType("*/*");
                        intentFile.addCategory(Intent.CATEGORY_OPENABLE);
                        try {
                            startActivityForResult(Intent.createChooser(intentFile, "请选择一个要上传的文件"), SELECT_FILE);
                            btnContainer.setVisibility(View.GONE);
                        } catch (android.content.ActivityNotFoundException ex) {
                            Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
                            ToastUtils.showShort(this.getApplication(), "请安装文件管理器");
                        }
                    }else {
                        IntentUtils.startActivityForString(this, GroupFileActivity.class, "groupID", this.TalkingID);
                    }

                    break;
                case R.id.btn_take_picture:
                    File outputImage = new File(Environment.getExternalStorageDirectory(), "/DCIM/Camera/" + System.currentTimeMillis() + ".jpg");
                    if (!outputImage.getParentFile().exists()) {
                        outputImage.getParentFile().mkdirs();
                    }
                    imageUri =Uri.fromFile(outputImage);//  FileProvider.getUriForFile(this,getPackageName()+".provider",outputImage);
                    Intent intentPic = new Intent();
                    intentPic.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intentPic.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                    intentPic.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intentPic, TAKE_PICTURE);
                    btnContainer.setVisibility(View.GONE);
                    break;

                case R.id.btn_voice_call:
                    IntentUtils.startActivityForString(this, VoiceCallActivity.class, "requestID", this.TalkingID);
                    btnContainer.setVisibility(View.GONE);
                    break;
                case R.id.btn_video_call:
                    if(this.TalkingType.equals(ConfigUtils.Person_Talking))//点对点视频
                    {
                        IntentUtils.startActivityForString(this, VideoCallActivity.class, "requestID", this.TalkingID);
                        btnContainer.setVisibility(View.GONE);
                    }else {
                        Intent intent1 = new Intent(ChatActivity.this, Group_Friend_SelectorActivity.class);
                        intent1.putExtra("groupFriendSelectorType", Group_Friend_SelectorType.VideoChatMemberInGroup);
                        intent1.putExtra("groupID",this.TalkingID);
                        ChatActivity.this.startActivityForResult(intent1,VideoMemberInGroup);
                    }

                    break;
                case R.id.btn_snapchat:
                     this.isSnapchating =true;
                    input_box.setActivated(true);
                    this.buttonSetModeVoice.setVisibility(View.GONE);//悄悄话暂时关闭发送语音功能
                    btnContainer.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }

            //通知自己的APP
            if (this.TalkingType.equals(ConfigUtils.Group_Talking)) {
                //OrayApplication.getInstance().notifyGroupInfo();
            }
        }
    }

    //点击右上角... 跳转到详情页面
    public void moveToMore(View view)
    {
        Log.d("d","跳转"+this.TalkingType);
        if(this.TalkingType.equals(ConfigUtils.Person_Talking))
        {
            Manager.getInstance().moveToUserDetail(this,this.TalkingID);
        }
        else if(this.TalkingType.equals(ConfigUtils.Group_Talking))
        {
            IntentUtils.startActivityForString(this, GroupDetailActivity.class, "requestID", this.TalkingID);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (resultCode != RESULT_OK) {
                return;
            }
            if (requestCode == TAKE_PICTURE) {

                //图片保存临时的，所以data为空
                byte[] bytes = null;
                 if (data == null) {
                    Bitmap bitmap = null;
                    try {
                        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        bytes = this.getZoomImageData(bitmap);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                } else if (data != null) {
                    if (data.hasExtra("data")) {
                        Bitmap bitmap = null;
                        try {
                            bitmap = data.getParcelableExtra("data");
                            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth() / 2, bitmap.getHeight() / 2, false);
                            bytes = this.getZoomImageData(scaledBitmap);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
                RichChatMessage chatContent=this.GetChatContent(bytes);
                if (sendMsg(chatContent)) {
                    ChatInfo info = ChatInfo.getChatImg(GGApplication.getInstance().getCurrentUser().getUserID(), this.TalkingID, FileUtils.getPath(ChatActivity.this, imageUri), true, new Date());
                    info.setRichChatMessage(chatContent);
                    addChatInfoAndDisplay(info);
                }

            } else if (requestCode == SELECT_IMG) {
                Uri uri = data.getData();
                Log.e("uri", uri.toString());
                ContentResolver cr = this.getContentResolver();
                Bitmap bitmap = null;
                try {
                    String fileName=com.oraycn.esbasic.helpers.FileHelper.getRealPathFromUri(this,uri);
                    bitmap=ImageHelper.loadBitmap(fileName,true);
                    Bitmap  bitmap1 = BitmapFactory.decodeStream(cr.openInputStream(uri));
                    byte[] bytes=this.getZoomImageData(bitmap);
                    RichChatMessage chatContent=this.GetChatContent(bytes);
                    if (sendMsg(chatContent)) {
                        ChatInfo info = ChatInfo.getChatImg(GGApplication.getInstance().getCurrentUser().getUserID(), this.TalkingID, FileUtils.getPath(ChatActivity.this, uri), true, new Date());
                        info.setRichChatMessage(chatContent);
                        addChatInfoAndDisplay(info);
                    }
                } catch (Exception ee) {
                    Log.e("Exception", ee.getMessage(), ee);
                }
            } else if (requestCode == SELECT_FILE) {
                Uri fileUri = data.getData();
                String filePath = FileUtils.getPath(ChatActivity.this, fileUri);
                FileMessage file = new FileMessage(filePath);
                String projectId = Manager.getInstance().sendFile(this.TalkingID, filePath);
                file.projectId = projectId;
                ChatInfo info = ChatInfo.getFileInfo(file, this.TalkingID, true, new Date());
                addChatInfoAndDisplay(info);
            } else if (requestCode == Share_Message) {
                if (this.currentShareChatInfo == null) {
                    return;
                }

                new Thread() {
                    @Override
                    public void run() {
                        sendShareMessage();
                    }
                }.start();

            }else if(requestCode== At_MemberInGroup)
            {
                Collection<UserBasicModel> users = (Collection<UserBasicModel>) HotCache.getValue4OnceOnly("memberSelected4At");
                if (users == null || users.size() == 0) {
                    return;
                }
                input.getText().replace(input.getText().length() - 1, input.getText().length(), "");//移除最后一个@字符
                for (UserBasicModel model : users) {
                    this.atSelectedUserManager.add(model.getUserID(), model.getUserName());
                    input.getText().append("@" + model.getUserName() + " ");
                }
            }else if(requestCode== VideoMemberInGroup){
                List<String> userIds = (List<String>) HotCache.getValue4OnceOnly("memberSelected4VideoChat");
                if (userIds != null && userIds.size() > 0) {
                    ///TO DO  邀请其他成员加入群视频聊
                    String currentUserID=ClientGlobalCache.getInstance().getCurrentUser().getUserID();
                    String videoGroupID=this.TalkingID+"_"+currentUserID+new Date().getTime();
                    userIds.add(currentUserID);//群成员加上自己
                    String userIDstr= StringHelper.ContactString(userIds,ConfigUtils.CommaSeparator);
                    String tag=videoGroupID+ConfigUtils.ColonSeparator+userIDstr;
                    Intent intent = new Intent(this, VideoChat4GroupActivity.class);
                    intent.putExtra("groupID", videoGroupID);
                    intent.putStringArrayListExtra("memberIDs", new ArrayList<String>(userIds));
                    intent.putExtra("tag",tag);
                    LogHelper.e("videoGroupID:"+videoGroupID+"   tag:"+tag);
                    this.startActivity(intent);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //获取最大尺寸为600的图片数据
    private byte[] getZoomImageData(Bitmap bitmap) {
        Size size = ImageHelper.getZoomSize(bitmap, 800);
        return ImageHelper.getZoomImageToByteArray(bitmap, size.getWidth(), size.getHeight(), true);
//        return  ImageHelper.bitmapToByteArray(bitmap,true);
    }

    //开始多人聊天
    private void startVideoGroupChat(List<String> userIds)
    {

    }

    //发送分享消息
    private void sendShareMessage()
    {
        try {
            List<String> userIds = (List<String>) HotCache.getValue4OnceOnly("UserBasicModels");
            RichChatMessage richChatMessage=currentShareChatInfo.getRichChatMessage();
            if(richChatMessage==null)
            {
                String imageUrl=currentShareChatInfo.getImageUrl();
                if(StringHelper.isNullOrEmpty(imageUrl))
                {
                    richChatMessage=this.GetChatContent(currentShareChatInfo.getContent());
                }
                else {
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.fromFile(new File(imageUrl))));
                    richChatMessage=this.GetChatContent(com.oraycn.esbasic.helpers.ImageHelper.bitmapToByteArray(bitmap,50,true));
                }
                currentShareChatInfo.setRichChatMessage(richChatMessage);
            }
            Manager.getInstance().sendChatMessage(userIds,currentShareChatInfo);
            Message message=mHandler.obtainMessage(3);
            mHandler.sendMessage(message);
        }catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    private void addChatInfoAndDisplay(ChatInfo info) {
        try {
            info.setIsGroupChat(this.TalkingType.equals(ConfigUtils.Group_Talking));
            infos.add(info);
            RichChatMessage richChatMessage=info.getRichChatMessage();

            if(richChatMessage!=null&&StringHelper.isNullOrEmpty(info.snapchatMessageID))
            {
                MessageItem item = null;
                if (this.TalkingType.equals(ConfigUtils.Person_Talking)) {
                    item = this.getMessageItem(richChatMessage, false,this.TalkingID);
                } else if (this.TalkingType.equals(ConfigUtils.Group_Talking)) {
                    item = this.getMessageItem(richChatMessage, true,this.TalkingID);
                }
                LastChatRecordPersister.getInstance().addOrUpdate(item);
            }
            Message msg = mHandler.obtainMessage(2);
            mHandler.sendMessage(msg);
            if (info.getFileMessage() != null) {
                return;
            }
            //系统消息不用存储到DB
            if(StringHelper.isNullOrEmpty(info.getSpeakerID()))
            {
                return;
            }
            ClientGlobalCache.getInstance().InsertChatMessageRecordInLocalDB(this.TalkingID,info);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private MessageItem getMessageItem(RichChatMessage info, boolean isGroup,String talkingID) {
        MessageItem item = new MessageItem();
        if (isGroup) {
            GGGroup group = ClientGlobalCache.getInstance().getGroup(talkingID);
            GGUser user = GGApplication.getInstance().getCurrentUser();
            item.title = group.getName();
            item.time = new Date();
            item.senderID = talkingID;
            item.lastWord = "[" + user.getName() + "]:" + LastChatRecordPersister.getInstance().getLastWord(info);
            item.isGroup = true;
        } else {
            GGUser user = ClientGlobalCache.getInstance().getUser(talkingID);
            String sourceName = user.getName();
            item.title = sourceName;
            item.time = new Date();
            item.senderID = talkingID;
            item.lastWord = LastChatRecordPersister.getInstance().getLastWord(info);
        }
        return item;
    }

    private boolean sendMsg(RichChatMessage msg) {
        boolean sended = false;
        if(SDKUtil.checkConnection()) {
            if (this.TalkingType.equals(ConfigUtils.Person_Talking)) {
                Manager.getInstance().sendChatMessage(this.TalkingID, msg);
            } else if (this.TalkingType.equals(ConfigUtils.Group_Talking)) {
                String atMemberIDs=this.getAtMemberIDs();
                Manager.getInstance().broadcastGroupChat(this.TalkingID, msg,atMemberIDs);
            }
            sended = true;
        }
        return sended;
    }

    //获取被@的成员列表，','分隔
    private String getAtMemberIDs()
    {
        String memberIDs = "";
        String text = this.input.getText().toString();
        HashMap<String, String> dic = this.atSelectedUserManager.ToHashMap();
        for (Map.Entry<String,String> kvp : dic.entrySet())
        {
            if (text.contains('@' + kvp.getValue()))
            {
                memberIDs += kvp.getKey() + ",";
            }
        }
        if (memberIDs.length() > 0)
        {
            memberIDs = memberIDs.substring(0, memberIDs.length() - 1);
        }
        this.atSelectedUserManager.clear();
        return memberIDs;
    }

    private void InitViewPager() {
        for (int i = 0; i < getPagerCount(); i++) {
            views.add(viewPagerItem(i));
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(16, 16);
            mDotsLayout.addView(dotsItem(i), params);
        }
        FaceVPAdapter mVpAdapter = new FaceVPAdapter(views);
        mViewPager.setAdapter(mVpAdapter);
        mDotsLayout.getChildAt(0).setSelected(true);
    }

    private View viewPagerItem(int position) {
//        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
//        View layout = inflater.inflate(R.layout.face_gridview, null);// 表情布局
//        GridView gridview = (GridView) layout.findViewById(R.id.chart_face_gv);
//        List subList = new ArrayList();
//        subList.addAll(MainActivity.staticFacesList
//                .subList(position * (columns * rows - 1),
//                        (columns * rows - 1) * (position + 1) > MainActivity.staticFacesList
//                                .size() ? MainActivity.staticFacesList.size() : (columns
//                                * rows - 1)
//                                * (position + 1)));
//        subList.add("emotion_del_normal.png");
//        FaceGVAdapter mGvAdapter = new FaceGVAdapter(subList, this);
//        gridview.setAdapter(mGvAdapter);
//        gridview.setNumColumns(columns);
//        // 单击表情执行的操作
//        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view,
//                                    int position, long id) {
//                try {
//                    String png = ((TextView) ((LinearLayout) view)
//                            .getChildAt(1)).getText().toString();
//                    if (!png.contains("emotion_del_normal")) {// 如果不是删除图标
//                        insert(getFace(png));
//                    } else {
//                        delete();
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//
//        return gridview;
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.face_gridview, null);// 表情布局
        GridView gridview = (GridView) layout.findViewById(R.id.chart_face_gv);
        List subList = new ArrayList();
        subList.addAll(MainActivity.staticFacesList
                .subList(position * (columns * rows ),
                        (columns * rows) * (position + 1) > MainActivity.staticFacesList
                                .size() ? MainActivity.staticFacesList.size() : (columns
                                * rows )
                                * (position + 1)));
        //subList.add("emotion_del_normal.png");
        FaceGVAdapter mGvAdapter = new FaceGVAdapter(subList, this);
        gridview.setAdapter(mGvAdapter);
        gridview.setNumColumns(columns);
        // 单击表情执行的操作
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                try {
                    String png = ((TextView) ((LinearLayout) view)
                            .getChildAt(1)).getText().toString();
                    if (!png.contains("emotion_del_normal")) {// 如果不是删除图标
                        insert(getFace(png));
                    } else {
                        delete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        return gridview;
    }

    private SpannableStringBuilder getFace(String png) {
        SpannableStringBuilder sb = new SpannableStringBuilder();
        try {
            String tempText = "#[" + png + "]#";
            sb.append(tempText);
            Bitmap image=BitmapFactory.decodeStream(getAssets().open(png));
            image.setDensity(200);
            sb.setSpan(new ImageSpan(ChatActivity.this, image), sb.length()- tempText.length(), sb.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb;
    }

    private void insert(CharSequence text) {
        int iCursorStart = Selection.getSelectionStart((input.getText()));
        int iCursorEnd = Selection.getSelectionEnd((input.getText()));
        if (iCursorStart != iCursorEnd) {
            input.getText().replace(iCursorStart, iCursorEnd, "");
        }
        int iCursor = Selection.getSelectionEnd((input.getText()));
        input.getText().insert(iCursor, text);
    }

    public void finish(View view) {
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        try {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if(chart_all.getVisibility()!=View.VISIBLE){
                    finish();
                }else{
                    chart_all.setVisibility(View.GONE);
                    bottom.setVisibility(View.VISIBLE);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    public void more(View view) {
        if(this.isSnapchating)
        {
            this.isSnapchating=false;
            input_box.setActivated(false);
            this.buttonSetModeVoice.setVisibility(View.VISIBLE);//关闭悄悄话开启发送语音功能
            return;
        }

        if (btnContainer.getVisibility() == View.GONE) {
            hideSoftInputView();
            btnMore.setVisibility(View.VISIBLE);
            if (chat_face_container != null) {
                chat_face_container.setVisibility(View.GONE);
            }
            btnContainer.setVisibility(View.VISIBLE);
        } else {
            btnContainer.setVisibility(View.GONE);
        }
    }

    public void clickModeKeyboard(View view) {
        btnContainer.setVisibility(View.GONE);
        input.setVisibility(View.VISIBLE);
        input.requestFocus();
        buttonSetModeKeyboard.setVisibility(View.GONE);
        buttonPressToSpeak.setVisibility(View.GONE);
        if (this.TalkingType.equals(ConfigUtils.Group_Talking)) {
            buttonSetModeVoice.setVisibility(View.GONE);
        } else {
            buttonSetModeVoice.setVisibility(View.VISIBLE);
        }
        btnMore.setSelected(false);//通过该设置来更改背景图片为蓝色
        if (TextUtils.isEmpty(input.getText())) {
            btnMore.setVisibility(View.VISIBLE);
            send.setVisibility(View.GONE);
        } else {
            btnMore.setVisibility(View.GONE);
            send.setVisibility(View.VISIBLE);
        }
        image_face.setVisibility(View.VISIBLE);
    }

    public void clickModeVoice(View view) {
        input.setVisibility(View.GONE);
        send.setVisibility(View.GONE);
        btnMore.setVisibility(View.VISIBLE);
        btnContainer.setVisibility(View.GONE);
        image_face.setVisibility(View.GONE);
        buttonSetModeKeyboard.setVisibility(View.VISIBLE);
        buttonSetModeVoice.setVisibility(View.GONE);
        btnMore.setSelected(true);//通过该设置来更改背景图片为黑色
        if (this.TalkingType.equals(ConfigUtils.Group_Talking)) {

            buttonPressToSpeak.setVisibility(View.GONE);
        }else{

            buttonPressToSpeak.setVisibility(View.VISIBLE);
        }

    }

    private void delete() {
        if (input.getText().length() != 0) {
            int iCursorEnd = Selection.getSelectionEnd(input.getText());
            int iCursorStart = Selection.getSelectionStart(input.getText());
            if (iCursorEnd > 0) {
                if (iCursorEnd == iCursorStart) {
                    if (isDeletePng(iCursorEnd)) {
                        String st = "#[face/png/f_static_000.png]#";
                        input.getText().delete(
                                iCursorEnd - st.length(), iCursorEnd);
                    } else {
                        input.getText().delete(iCursorEnd - 1,
                                iCursorEnd);
                    }
                } else {
                    input.getText().delete(iCursorStart,
                            iCursorEnd);
                }
            }
        }
    }

    private boolean isDeletePng(int cursor) {
        String st = "#[face/png/f_static_000.png]#";
        String content = input.getText().toString().substring(0, cursor);
        if (content.length() >= st.length()) {
            String checkStr = content.substring(content.length() - st.length());
            String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(checkStr);
            return m.matches();
        }
        return false;
    }

    private ImageView dotsItem(int position) {
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.dot_image, null);
        ImageView iv = (ImageView) layout.findViewById(R.id.face_dot);
        iv.setId(position);
        return iv;
    }

    private int getPagerCount() {
        int count = MainActivity.staticFacesList.size();
        return count % (columns * rows - 1) == 0 ? count / (columns * rows - 1)
                : count / (columns * rows - 1) + 1;
    }

    private void initStaticFaces() {
        try {
            MainActivity.staticFacesList = new ArrayList();
            String[] faces = getAssets().list("face/png");
            // 将Assets中的表情名称转为字符串一一添加进staticFacesList
            for (int i = 0; i < faces.length; i++) {
                MainActivity.staticFacesList.add(faces[i]);
            }
            // 去掉删除图片
            MainActivity.staticFacesList.remove("emotion_del_normal.png");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private RichChatMessage GetChatContent(byte[] bytes)
    {
        RichChatMessage chatContent = new RichChatMessage();
        chatContent.setText(" ");
        NonText nonText = new NonText();
        nonText.setChatBoxElementType(ChatBoxElemnetType.Image);
        nonText.setImage(bytes);
        chatContent.getNonTextHashMap().put(0, nonText);
        return chatContent;
    }

    private RichChatMessage GetChatContent(String chatStr) {
        StringBuilder stringBuilder = new StringBuilder(chatStr);
        RichChatMessage chatContent = new RichChatMessage();
        HashMap<Integer, NonText> hashMap = new HashMap<Integer, NonText>();
        for (int i = 0; i < stringBuilder.length(); i++) {
            if (stringBuilder.charAt(i) == '#') {
                if (stringBuilder.length() - 1 > i + 27) {
                    String tempStr = stringBuilder.substring(i + 11, i + 27);
                    if (MainActivity.staticFacesList.contains(tempStr)) {
                        NonText nonText = new NonText();
                        nonText.setChatBoxElementType(ChatBoxElemnetType.Emotion);
                        nonText.setInnerEmotionIndex(MainActivity.staticFacesList.indexOf(tempStr));
                        hashMap.put(i, nonText);
                        stringBuilder.replace(i, i + 29, " ");
                    }
                }
            }
        }

        chatContent.setNonTextHashMap(hashMap);
        chatContent.setText(stringBuilder.toString());
        return chatContent;
    }

    private List<ChatInfo> getHistoryChatInfo() {
        return ChatMessageRecordPersister.getInstance().getPage(this.TalkingID, GGApplication.getInstance().getCurrentUser().getUserID(), pageSize, infos.size());
    }

    public void onEventMainThread(UserEvent event) {
        if (this.TalkingID.equals(event.userID)) {
            updateUserStatus(true);
        }
    }

    public void onEventMainThread(GroupInfoChangedEvent event)
    {
        if (TalkingID.equals(event.groupID)) {
            this.setGroupHeader();
        }
    }

    public void onEventMainThread(GroupUserChangedEvent event)
    {
        if (TalkingID.equals(event.groupID)) {
            this.setGroupHeader();
        }
    }

    public void onEventMainThread(UserInfoChangedEvent event)
    {
        if(this.TalkingID.equals(ClientGlobalCache.getInstance().getCurrentUser().getUserID()))
        {
            return;
        }
        if (TalkingID.equals(event.UserID)) {
            GGUser GGUser = ClientGlobalCache.getInstance().getUser(event.UserID);
            header.setText(GGUser.getName());
        }
    }

    public void onEventMainThread(FriendCommentNameChangedEvent event)
    {
        if(event.FriendID.equals(this.TalkingID))
        {
            this.header.setText(event.CommentName);
        }
    }

    public void onEventMainThread(SnapchatMessageReadEvent event)
    {
        if(!event.DestUserID.equals(this.TalkingID))
        {
            return;
        }
        for (int i=0;i<this.infos.size();i++)
        {
            if(this.infos.get(i).snapchatMessageID.equals(event.MessageID))
            {
                this.onSnapchatMessageTimeover(i);
                return;
            }
        }

    }

    public void onEventMainThread(ChatEvent event) {
        if (this.TalkingType.equals(ConfigUtils.Group_Talking) && !event.isGroupChat)//如果是group聊天窗口且是个人所发消息
        {
            return;
        }
        if (this.TalkingType.equals(ConfigUtils.Person_Talking) && event.isGroupChat)//如果是group聊天窗口且是个人所发消息
        {
            return;
        }
        if(!this.TalkingID.equals(event.groupID))
        {
            return;
        }
        if(event.clientType== ClientType.ANDROID && event.groupID.equals(ClientGlobalCache.getInstance().getCurrentUser().getUserID()))
        {
            return;
        }
        ChatInfo chatInfo=null;
        if (!event.groupID.isEmpty()) {
            if (event.type == ChatEventType.Vibration) {
                vibrator.vibrate(200);
                return;
            } else if (event.type == ChatEventType.RichChatMessage) {
                if (event.isSystemMsg) {
                    chatInfo = ChatInfo.getSystemInfo(event.groupID, event.msg.getText());
                } else {
                    chatInfo = ChatInfo.getChatInfo4Received(event.sourceID, this.TalkingID, event.msg, event.isEcho, event.msg.TransferTime);
//                    chatInfo = ChatInfo.getChatInfo(event.sourceID, this.TalkingID, event.msg, !event.groupID.equals(TalkingID),event.msg.TransferTime);
                }
            } else if (event.type == ChatEventType.AudioMessage) {
                chatInfo = ChatInfo.getChatInfo(event.sourceID, this.TalkingID, event.audioMessage, !event.groupID.equals(TalkingID), new Date());

            } else if (event.type == ChatEventType.FileMessage) {
                return;
//                chatInfo = ChatInfo.getFileInfo(event.fileMessage,this.TalkingID, false,new Date());
//                addChatInfoAndDisplay(info);
            }
            chatInfo.setIsGroupChat(event.isGroupChat);
            chatInfo.snapchatMessageID =event.snapchatMessageID;
            addChatInfoAndDisplay(chatInfo);
        }
    }

    public void onEventMainThread(FileEvent event) {
        if(event.FileTransferUseType == FileTransferUseType.Comment4NDisk){
            return;
        }
        switch (event.Type) {
            case FileEvent.FILE_REQ: {
                if(!event.Sender.equals(this.TalkingID))
                {
                    return;
                }
                FileMessage file = new FileMessage(event.FilePath, event.FileName, (int) event.FileSize, event.TransferSize, event.ProjectId);
                ChatInfo info = ChatInfo.getFileInfo(file,this.TalkingID, event.Sender.equals(ClientGlobalCache.getInstance().getCurrentUser().getUserID()),new Date());
                addChatInfoAndDisplay(info);
            }
            break;
            case FileEvent.FILE_RESP:
                mLvAdapter.updateProcess(event);
            break;
            case FileEvent.FILE_PROCESS:
                mLvAdapter.updateProcess(event);
                break;
            case FileEvent.CANCEL_TRANSFERING:
                mLvAdapter.updateProcess(event);
                break;
            case FileEvent.FILE_TRANS_DISRUPPTTED:
                ChatInfo infoGet = null;
                for (ChatInfo info : infos) {
                    FileMessage fileMessage = info.getFileMessage();
                    if (fileMessage != null && fileMessage.projectId.equals(event.ProjectId)) {
                        if (event.DisrupttedType == FileEventListener.FileTransDisrupttedType.AnswerFileRequestOnOtherDevice) {
                            info.setFileStateMsg("已在其他设备上处理！");
                        }
                        info.setAcceptFile(false);
                        infoGet = info;
                        break;
                    }
                }
                if (infoGet.isFromSession()) {
                    infoGet.setIsFromSession(false);
                    ClientGlobalCache.getInstance().UpdateChatMessageRecordInLocalDB(this.TalkingID,infoGet);
                } else {
                    ClientGlobalCache.getInstance().InsertChatMessageRecordInLocalDB(this.TalkingID,infoGet);
                }
                mLvAdapter.updateProcess(event);
                if (event.DisrupttedType == FileEventListener.FileTransDisrupttedType.AnswerFileRequestOnOtherDevice) {
                    Toast.makeText(ChatActivity.this, "已经在其他设备上回应了对应传送'" + infoGet.getFileMessage().fileName + "'文件的请求！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(ChatActivity.this, "传输已终止", Toast.LENGTH_SHORT).show();
                }
                break;
            case FileEvent.FILE_COMPLETED: {
                ChatInfo infoGet1 = null;
                int position=0;
                for (int i=0;i<infos.size();i++)
                {
                    ChatInfo info=infos.get(i);
                    FileMessage fileMessage=info.getFileMessage();

                    if (fileMessage != null && info.getFileMessage().projectId.equals(event.ProjectId)) {
                        info.setFileHasDown(true);
                        if(StringHelper.isNullOrEmpty(fileMessage.filePath))
                        {
                            fileMessage.filePath=ConfigUtils.SDFileSavePath+fileMessage.fileName;
                        }
                        infoGet1 = info;
                        position=i;
                        break;
                    }
                }
                if (infoGet1.isFromSession()) {
                    infoGet1.setIsFromSession(false);
                    ClientGlobalCache.getInstance().UpdateChatMessageRecordInLocalDB(this.TalkingID,infoGet1);
                } else {
                    ClientGlobalCache.getInstance().InsertChatMessageRecordInLocalDB(this.TalkingID,infoGet1);
                }
                mLvAdapter.updateProcess(event);
//                mLvAdapter.updateItem(position,mListView);
                Toast.makeText(ChatActivity.this, "文件传输完成，保存地址："+infoGet1.getFileMessage().filePath, Toast.LENGTH_SHORT).show();
            }
            break;
        }
    }

    //region GroupBan 禁言
    public void onEventMainThread(GroupBan4UserEvent event) {
        if(this.isExistAllGroupBan||!this.TalkingID.equals(event.GroupID)||this.isGroupCreator)
        {
            return;
        }
        this.setControl_GroupBan(true);
        Manager.getInstance().sendSystemMessage(event.GroupID,"您已被管理员禁言",true);
    }
    public void onEventMainThread(RemoveGroupBan4UserEvent event)
    {
        if(this.isExistAllGroupBan||!this.TalkingID.equals(event.GroupID)) {
            return;
        }
        this.setControl_GroupBan(false);
        Manager.getInstance().sendSystemMessage(event.GroupID,"您已被管理员解除禁言",true);
    }

    public void onEventMainThread(GroupBan4GroupEvent event)
    {
        if(this.isGroupCreator)
        {
            return;
        }
        this.isExistAllGroupBan = true;
        this.setControl_GroupBan(true);
        Manager.getInstance().sendSystemMessage(event.GroupID,"管理员开启了全员禁言",true);
    }

    public void onEventMainThread(RemoveGroupBan4GroupEvent event)
    {
        if(this.isGroupCreator)
        {
            return;
        }
        this.isExistAllGroupBan = false;
        this.setControl_GroupBan(false);
        Manager.getInstance().checkGroupBan4CurrentUser(this.TalkingID);
        Manager.getInstance().sendSystemMessage(event.GroupID,"管理员关闭了全员禁言",true);
    }

    public void onEventMainThread(GroupDeletedNotifyEvent event)
    {
        if(!this.TalkingID.equals(event.groupID))
        {
            return;
        }
        ToastUtils.showLong(this,"该讨论组已经被解散");
        finish();
    }

    public void onEventMainThread(FriendDeletedNotifyEvent event)
    {
        if(!this.TalkingID.equals(event.getGGUser().getUserID()))
        {
            return;
        }
        ToastUtils.showLong(this,"好友已被删除");
        finish();
    }



    private boolean isGroupCreator()
    {
        if (!this.TalkingType.equals(ConfigUtils.Group_Talking))
        {
            return false;
        }
        GGGroup group=ClientGlobalCache.getInstance().getGroup(this.TalkingID);
        if(group==null)
        {
            return false;
        }
        return group.getCreatorID().equals(ClientGlobalCache.getInstance().getCurrentUser().getUserID());
    }
    //endregion

    private void setGroupHeader()
    {
        ct_photo.setVisibility(View.GONE);
        GGGroup group = ClientGlobalCache.getInstance().getGroup(this.TalkingID);
        if (group != null) {
            header.setText(group.getName() + "(" + group.getChildCount() + "人)");
        } else {
            header.setText(group.getName() + "(" + 0 + ")");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        header.forceLayout();
        GGApplication.getInstance().TALKINGUSER = this.TalkingID;
        if (this.TalkingType.equals(ConfigUtils.Person_Talking)) {
            bottom.setVisibility(View.VISIBLE);
            bottom_ban.setVisibility(View.GONE);
            if(ClientGlobalCache.getInstance().getCurrentUser().isInMyBlackList(this.TalkingID))
            {
                this.setBlackBlackListView("黑名单用户禁止聊天");
            }
            if(SDKUtil.checkConnection()&&!ClientGlobalCache.getInstance().getCurrentUser().isFriend(this.TalkingID))
            {   //陌生人聊天，判断是否在对方的黑名单中
                if( Manager.getInstance().isInHisBlackList(this.TalkingID))
                {
                    this.setBlackBlackListView("对方已将您加入黑名单禁止聊天");
                }
            }
        }

        /**
         * 软键盘弹出收起监听
         */
        OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener = new OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                Log.d("chat","键盘显示 高度 : " + height);
                startAnim(bottom,-height);
                RelativeLayout.LayoutParams  params= (RelativeLayout.LayoutParams)mListView.getLayoutParams();
                params.height=mListView.getMeasuredHeight()-height;
                params.removeRule(RelativeLayout.ABOVE);
                mListView.setLayoutParams(params);
                Message msg = mHandler.obtainMessage(2);
                mHandler.sendMessage(msg);
            }
            @Override
            public void keyBoardHide(int height) {
                Log.d("chat","键盘隐藏 高度 : " + height);
                startAnim(bottom,0);
                RelativeLayout.LayoutParams  params= (RelativeLayout.LayoutParams)mListView.getLayoutParams();
                params.height=-1;
                params.addRule(RelativeLayout.ABOVE,R.id.bottom);
                mListView.setLayoutParams(params);
            }
        };
        PreventKeyboardBlockUtil.getInstance(this).setListener(onSoftKeyBoardChangeListener);
        PreventKeyboardBlockUtil.getInstance(this).setBtnView(header).register();
    }

    private boolean lastNeedTopUpPage=true;//上一次是否顶起页面
     private int keyBoardHeight=0;//软键盘弹起的高度
    private int getListViewContentHeight()
    {
        int h=0;
        for (int i =0;i<infos.size();i++)
        {
            View view= mLvAdapter.getView(i,null,mListView);
            view.measure(0,0);
            h+=view.getMeasuredHeight();
        }
        return h;
    }

    AnimatorSet animSet = new AnimatorSet();

    void startAnim(@NonNull View view, int transY) {
        @SuppressLint({"NewApi", "LocalSuppress"}) float curTranslationY = view.getTranslationY();
        @SuppressLint({"NewApi", "LocalSuppress"}) ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "translationY", curTranslationY, transY);
        animSet.play(objectAnimator);
        animSet.setDuration(0);
        animSet.start();
    }

    @Override
    protected void onDestroy() {
        GGApplication.getInstance().TALKINGUSER = "";
        this.closeAudioContext();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
   protected void onPause() {
        super.onPause();
        this.closeAudioContext();
        PreventKeyboardBlockUtil.getInstance(this).unRegister();
    }

    @Override
    public void onRefresh() {
        new Thread() {
            @Override
            public void run() {
                try {
                    sleep(500);
                    List<ChatInfo> list = getHistoryChatInfo();
                    Message msg = mHandler.obtainMessage(0,list);
                    mHandler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public void hideSoftInputView() {
        InputMethodManager manager = ((InputMethodManager) this
                .getSystemService(Activity.INPUT_METHOD_SERVICE));
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
//                manager.hideSoftInputFromWindow(getCurrentFocus()
//                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                manager.hideSoftInputFromWindow(input.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    class PageChange implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            for (int i = 0; i < mDotsLayout.getChildCount(); i++) {
                mDotsLayout.getChildAt(i).setSelected(false);
            }
            mDotsLayout.getChildAt(arg0).setSelected(true);
        }
    }

    private class ImageAlertClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            int state = v.getVisibility();
            if (state == View.GONE || state == View.INVISIBLE) {
                chart_all.setVisibility(View.VISIBLE);
                bottom.setVisibility(View.GONE);
            } else {
                chart_all.setVisibility(View.GONE);
                bottom.setVisibility(View.VISIBLE);
            }
        }
    }
}

